package jane.mvc.actionresults;

import jane.mvc.engine.JaneMVCContext;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;

public abstract class ActionResult implements IActionResult
{

	private Object content = new Object();
	private String contentType = "text/html";

	public Object getContent()
	{
		return content;
	}

	public void setContent(Object content)
	{
		this.content = content;
	}

	public String getContentType()
	{
		return contentType;
	}

	public void setContentType(String contentType)
	{
		this.contentType = contentType;
	}

	public void executeResult(JaneMVCContext context)
	{

		context.getResponse().setContentType(this.getContentType());

		// TODO set return in bytes, currently only text is being returned
		// (getOutputStream)

		if (this.isText())
		{

			PrintWriter pw = null;
			try
			{
				pw = context.getResponse().getWriter();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (pw != null)
			{

				pw.write((String) this.getContent());

				pw.close();
			}
		} else
		{
			ServletOutputStream out = null;
			try
			{
				out = context.getResponse().getOutputStream();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (out != null)
			{

				try
				{
					out.write((byte[]) this.getContent());
					out.close();
				} catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}

	}
}
